<?php

class Router
{
	private static
		$controllers_strings = array(
			 ''                 => 'Index',
			 'home'             => 'Home',
			 'clearclasscache'  => 'ClearClassCache',
			 'memcachestats'    => 'MemCacheStats',
			 'playground'       => 'PlayGround',
			 'smreport'         => 'ServiceMonitorReport'
		),
			  
		$controllers_reg_exps = array(),
			  
		$actions_strings = array(
			 'Home' => array(
				  ''     => 'Index',
				  'demo' => 'Demo',
			 ),
		),
			  
		$actions_reg_exps = array();
	
	public static function GetRoute()
	{
		$route = new Route();
		
		// удаляем слэши с начале и в конце строки
		//$request_uri = preg_replace('/^\/|\/$/','',$_SERVER['REQUEST_URI']);
		$request_uri = preg_replace('/^\/|\/$/','',$_SERVER['REDIRECT_URL']);
		
		if (!ALLOW_CAPS_URL)
		{
			// переводим в нижний регистр
			$request_uri = strtolower($request_uri);
		}

		// разбиваем строку запроса
		$path = explode('/', $request_uri);
		
		if (is_array($path))
		{
			$route->controller = self::GetControllerName(array_shift($path));
			$route->action = self::GetActionName($path, $route->controller);
			$route->params = $path;
		}
		
		$route->controller .= "Controller";
		
		return $route;
	}
	
	private function GetControllerName($controller_path)
	{
		if (isset(self::$controllers_strings[$controller_path]))
		{
			return self::$controllers_strings[$controller_path];
		}
		
		foreach (self::$controllers_reg_exps as $k => $v)
		{
			if (preg_match($k, $controller_path))
			{
				return $v;
			}
		}
		
		return "NotFound";
	}
	
	private function GetActionName(&$path, $controller)
	{
		$action = array_shift($path);
		
		if ($action)
		{
			if (  isset(self::$actions_strings[$controller])
				&& is_array(self::$actions_strings[$controller]))
			{
				if (isset(self::$actions_strings[$controller][$action]))
				{
					return self::$actions_strings[$controller][$action];
				}
			}
			
			if (  isset(self::$actions_reg_exps[$controller])
				&& is_array(self::$actions_reg_exps[$controller]))
			{
				foreach (self::$actions_reg_exps[$controller] as $k => $v)
				{
					if (preg_match($k, $action))
					{
						return $v;
					}
				}
			}
			
			array_unshift($path, $action);
		}
		
		return "Index";
	}
}

?>
